package com.example.idachuappone.person.item;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.idachuappone.BaseActivity;
import com.example.idachuappone.R;
import com.example.idachuappone.person.method.AddressMethod;
import com.example.idachuappone.person.method.AddressMethod.SetAddress;
import com.example.idachuappone.promptly.entity.Addresses;
import com.example.idachuappone.promptly.entity.UserInfo;
import com.example.idachuappone.promptly.item.AddAddressActivity;
import com.example.idachuappone.promptly.item.SelectAddressActivity;
import com.example.idachuappone.utils.AppShareData;
import com.example.idachuappone.utils.Constant;
import com.example.idachuappone.utils.CusProSmallBgDialog;
import com.example.idachuappone.utils.MainToast;
import com.example.idachuappone.utils.NetUtil;
import com.example.idachuappone.utils.PrefUtil;
import com.lidroid.xutils.bitmap.BitmapGlobalConfig.BitmapCacheManagementTask;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class CookAddressListPersonActivity extends BaseActivity implements OnClickListener, OnItemClickListener,
		OnItemLongClickListener {
	private ListView Lv_address_list;
	private CookAddressAdapter adapter;
	private Button btn_back;
	private Button btn_index;
	private CusProSmallBgDialog cusProDialog;
	private boolean isNoData;
	private boolean isupdateposition;
	private LinearLayout ll_no_data;
	private LinearLayout ll_no_network;
	private UserInfo userInfo;

	class AnonymousClass_3 implements DialogInterface.OnClickListener {
		private final/* synthetic */int val$position;

		AnonymousClass_3(int i) {
			this.val$position = i;
		}

		@Override
		public void onClick(DialogInterface dialog, int which) {
			Map<String, String> map = new HashMap();
			map.put("id", CookAddressListPersonActivity.this.userInfo.getAddresses().get(this.val$position).getId());
			NetUtil.post(CookAddressListPersonActivity.this, Constant.DELETE_ADDRESSS, map,
					new RequestCallBack<String>() {
						@Override
						public void onStart() {
							super.onStart();
							CookAddressListPersonActivity.this.cusProDialog.setMsg("\u5220\u9664\u5730\u5740\u4e2d...");
							CookAddressListPersonActivity.this.cusProDialog.show();
						}

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							CookAddressListPersonActivity.this.cusProDialog.dismiss();
							try {
								JSONObject jsonObject = new JSONObject(NetUtil.unescapeUnicode(responseInfo.result));
								if (jsonObject.getInt("code") == 10000) {
									AppShareData.isRefreshAddressChoose = true;
									CookAddressListPersonActivity.this.initDate();
									return;
								}
								MainToast.show(CookAddressListPersonActivity.this, jsonObject.getString("error"), 0);
							} catch (JSONException e) {
								e.printStackTrace();
								MainToast.show(CookAddressListPersonActivity.this,
										CookAddressListPersonActivity.this.getString(R.string.app_error), 0);
							}
						}

						@Override
						public void onFailure(HttpException arg0, String arg1) {
							CookAddressListPersonActivity.this.cusProDialog.dismiss();
							MainToast.show(CookAddressListPersonActivity.this, CookAddressListPersonActivity.this
									.getResources().getString(R.string.netFail), 0);
						}
					});
		}
	}

	class CookAddressAdapter extends BaseAdapter {
		private Context context;
		private int index;
		private List<Addresses> list;

		public void setIndex(int index) {
			this.index = index;
		}

		public void setList(List<Addresses> list) {
			this.list = list;
		}

		public CookAddressAdapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			return this.list == null ? 0 : this.list.size();
		}

		@Override
		public Object getItem(int position) {
			return this.list == null ? null : (Addresses) this.list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView == null) {
				convertView = LinearLayout.inflate(this.context, R.layout.simple_cook_address_list_person, null);
				viewHolder = new ViewHolder();
				viewHolder.tv_address = (TextView) convertView.findViewById(R.id.tv_address);
				viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
				viewHolder.tv_phone = (TextView) convertView.findViewById(R.id.tv_phone);
				viewHolder.ll_default = (LinearLayout) convertView.findViewById(R.id.ll_default);
				viewHolder.img_check = (ImageView) convertView.findViewById(R.id.img_check);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			Addresses addresses = this.list.get(position);
			String address = addresses.getArea() + addresses.getCommunity() + addresses.getDoor_number();
			if (position == 0) {
				CharSequence text = "\u2605 " + address;
				SpannableStringBuilder builder = new SpannableStringBuilder(text);
				Matcher matcher = Pattern.compile("\u2605").matcher(text);
				while (matcher.find()) {
					builder.setSpan(new ImageSpan(this.context, 2130837635), matcher.start(), matcher.end(),
							17);
				}
				viewHolder.tv_address.setText(builder);
				viewHolder.ll_default.setBackgroundColor(Color.parseColor("#e5e5e6"));
				viewHolder.img_check.setVisibility(0);
			} else {
				viewHolder.ll_default.setBackgroundResource(R.color.white);
				viewHolder.img_check.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				viewHolder.tv_address.setText(address);
			}
			viewHolder.tv_name.setText(addresses.getName());
			viewHolder.tv_phone.setText(addresses.getPhone());
			return convertView;
		}
	}

	private class ViewHolder {
		private ImageView img_check;
		private LinearLayout ll_default;
		private TextView tv_address;
		private TextView tv_name;
		private TextView tv_phone;

		private ViewHolder() {
		}
	}

	public CookAddressListPersonActivity() {
		this.isupdateposition = false;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cook_address_list_person);
		this.cusProDialog = new CusProSmallBgDialog(this);
		this.cusProDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				CookAddressListPersonActivity.this.cusProDialog.dismiss();
			}
		});
		initView();
		initDate();
	}

	private void initDate() {
		AddressMethod.getAddressList(this, this.cusProDialog, new SetAddress() {
			@Override
			public void onSuccess(String result) {
				CookAddressListPersonActivity.this.ll_no_network
						.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				try {
					JSONObject jsonObject = new JSONObject(NetUtil.unescapeUnicode(result));
					if (jsonObject.getInt("code") == 10000) {
						CookAddressListPersonActivity.this.userInfo = new UserInfo();
						CookAddressListPersonActivity.this.userInfo.parseJson(jsonObject.getJSONObject("data"));
						if (CookAddressListPersonActivity.this.userInfo.getAddresses() == null
								|| CookAddressListPersonActivity.this.userInfo.getAddresses().size() <= 0) {
							CookAddressListPersonActivity.this.ll_no_data.setVisibility(0);
							CookAddressListPersonActivity.this.isNoData = true;
							return;
						}
						CookAddressListPersonActivity.this.initAdapter(0);
						CookAddressListPersonActivity.this.ll_no_data
								.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
						CookAddressListPersonActivity.this.isNoData = false;
						if (CookAddressListPersonActivity.this.isupdateposition) {
							PrefUtil prefUtil = PrefUtil.getInstance(CookAddressListPersonActivity.this);
							prefUtil.setFimallyLocateCoor(new StringBuilder(
									String.valueOf(CookAddressListPersonActivity.this.userInfo.getAddresses().get(0)
											.getLng())).append(",")
									.append(CookAddressListPersonActivity.this.userInfo.getAddresses().get(0).getLat())
									.toString());
							prefUtil.setArea(CookAddressListPersonActivity.this.userInfo.getAddresses().get(0)
									.getArea());
							prefUtil.setXiaoQu(CookAddressListPersonActivity.this.userInfo.getAddresses().get(0)
									.getCommunity());
							prefUtil.setDoor(CookAddressListPersonActivity.this.userInfo.getAddresses().get(0)
									.getDoor_number());
							prefUtil.setName(CookAddressListPersonActivity.this.userInfo.getAddresses().get(0)
									.getName());
							prefUtil.setUserAddressId(CookAddressListPersonActivity.this.userInfo.getAddresses().get(0)
									.getId());
							prefUtil.setPhone(CookAddressListPersonActivity.this.userInfo.getAddresses().get(0)
									.getPhone());
							CookAddressListPersonActivity.this.isupdateposition = false;
						}
					} else if (jsonObject.getInt("code") == 300) {
						MainToast.show(CookAddressListPersonActivity.this, jsonObject.getString("error"), 0);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFail() {
				CookAddressListPersonActivity.this.ll_no_network.setVisibility(0);
			}
		});
	}

	private void initAdapter(int index) {
		this.adapter.setIndex(index);
		this.adapter.setList(this.userInfo.getAddresses());
		this.adapter.notifyDataSetChanged();
	}

	private void initView() {
		this.ll_no_network = (LinearLayout) findViewById(R.id.ll_no_network);
		this.ll_no_network.setOnClickListener(this);
		this.btn_index = (Button) findViewById(R.id.btn_index);
		this.btn_index.setOnClickListener(this);
		this.btn_back = (Button) findViewById(R.id.btn_back);
		this.btn_back.setOnClickListener(this);
		this.Lv_address_list = (ListView) findViewById(R.id.Lv_address_list);
		this.Lv_address_list.setOnItemClickListener(this);
		this.Lv_address_list.setOnItemLongClickListener(this);
		this.adapter = new CookAddressAdapter(this);
		this.Lv_address_list.setAdapter(this.adapter);
		this.ll_no_data = (LinearLayout) findViewById(R.id.ll_no_data);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back /* 2131165198 */:
			finish();
		case R.id.btn_index /* 2131165213 */:
			Intent intent = new Intent(this, AddAddressActivity.class);
			intent.putExtra("isNoData", this.isNoData);
			startActivityForResult(intent, BitmapCacheManagementTask.MESSAGE_FLUSH);
		case R.id.ll_no_network /* 2131165232 */:
			initDate();
		default:
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == 4) {
			setResult(-1);
			finish();
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		boolean temp;
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == -1) {
			temp = data.getBooleanExtra("isupdateposition", false);
			if (temp) {
				this.isupdateposition = temp;
			}
			AppShareData.isRefreshAddressChoose = true;
			initDate();
		}
		if (requestCode == 2 && resultCode == -1) {
			temp = data.getBooleanExtra("isNoData", false);
			if (temp) {
				this.isupdateposition = temp;
			}
			AppShareData.isRefreshAddressChoose = true;
			initDate();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (AppShareData.isRefreshAddress) {
			initDate();
			this.isupdateposition = true;
			AppShareData.isRefreshAddressChoose = true;
			AppShareData.isRefreshAddress = false;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View arg1, int position, long arg3) {
		Intent intent = new Intent(this, SelectAddressActivity.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable("address", this.userInfo.getAddresses().get(position));
		bundle.putInt("position", position);
		intent.putExtras(bundle);
		startActivity(intent);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> adapterView, View arg1, int position, long arg3) {
		new Builder(this)
				.setMessage("\u60a8\u786e\u5b9a\u8981\u5220\u9664\u8fd9\u6761\u5386\u53f2\u5730\u5740\u5417\uff1f")
				.setPositiveButton("\u786e\u5b9a", new AnonymousClass_3(position))
				.setNegativeButton("\u53d6\u6d88", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				}).create().show();
		return true;
	}
}
